package com.draemoncode.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import javax.swing.JFrame;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MinaAcceptListener {
	
	private JFrame view;
	
	private DefaultMinaIoHandlerAdapter ioHandlerAdapter;
	
	public JFrame getView() {
		return view;
	}

	public void setView(JFrame view) {
		this.view = view;
	}
	
	public DefaultMinaIoHandlerAdapter getIoHandlerAdapter() {
		return ioHandlerAdapter;
	}

	public void setIoHandlerAdapter(DefaultMinaIoHandlerAdapter ioHandlerAdapter) {
		this.ioHandlerAdapter = ioHandlerAdapter;
	}

	public void init(int port) {
		try {
			// 创建服务端监控线程
			NioSocketAcceptor acceptor = new NioSocketAcceptor();
			acceptor.getSessionConfig().setReadBufferSize(2048);
			// 设置日志记录器
			acceptor.getFilterChain().addLast("logger", new LoggingFilter());
			// 设置编码过滤器
			acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue())));
			// 指定业务逻辑处理器
			DefaultMinaIoHandlerAdapter handler = new DefaultMinaIoHandlerAdapter(view);
			ioHandlerAdapter = handler;
			acceptor.setHandler(handler);
			// 设置端口号
			acceptor.bind(new InetSocketAddress(port));
			// 启动监听线程
			acceptor.bind();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
